我有几个表有不同数量和类型的列,以及一个共同的列.
+--------+---------+------------+-------------+ | person | beardID | beardStyle | beardLength | +--------+---------+------------+-------------+ +--------+-------------+----------------+ | person | moustacheID | moustacheStyle | +--------+-------------+----------------+
我想获取与共享列的给定值匹配的所有结果.我可以使用这样的多个select语句来做到这一点:
SELECT * FROM beards WHERE person = "bob"
和
SELECT * FROM moustaches WHERE person = "bob"
但这需要多次MysqL API调用,这似乎效率低下.我希望我可以使用UNION ALL在单个API调用中获取所有结果,但UNION要求表具有相同数量和相似类型的列.我可以编写一个SELECT语句,通过添加具有NULL值的列来手动填充每个表的结果,但是对于具有更多列的更多表,这将很快变得无法管理.
我正在寻找一个大致如下的结果集:
+--------+---------+------------+-------------+-------------+----------------+ | person | beardID | beardStyle | beardLength | moustacheID | moustacheStyle | +--------+---------+------------+-------------+-------------+----------------+ | bob | 1 | rasputin | 1 | | | +--------+---------+------------+-------------+-------------+----------------+ | bob | 2 | samson | 12 | | | +--------+---------+------------+-------------+-------------+----------------+ | bob | | | | 1 | fu manchu | +--------+---------+------------+-------------+-------------+----------------+
有没有办法实现快速和可维护的目标?或者我最好为每个表运行单独的查询?
澄清:
我不是在寻找笛卡尔积.我不想为胡子和胡子的每一个组合排一排,我想为每个胡须排一排,每个胡子排一排.
因此,如果有3个匹配的胡须和2个匹配的胡须,我应该得到5行,而不是6行.
这应该工作正常:
原文链接:https://www.f2er.com/php/134398.htmlSELECT * FROM `beards` b LEFT OUTER JOIN `mustaches` ON (0) WHERE person = "bob" UNION ALL SELECT * FROM `beards` b RIGHT OUTER JOIN `mustaches` ON (0) WHERE person = "bob"
您不必自己处理列.左外连接和右外连接完成这项工作.
不幸的是,MysqL没有完整的连接.这就是你必须用联盟这样做的原因
SELECT * FROM `customer` b LEFT OUTER JOIN `charges` ON (0) LEFT OUTER JOIN `day` ON (0) UNION SELECT * FROM `customer` b RIGHT OUTER JOIN `charges` ON (0) LEFT OUTER JOIN `day` ON (0) UNION SELECT * FROM `customer` b LEFT OUTER JOIN `charges` ON (0) RIGHT OUTER JOIN `day` ON (0)
这是我做的本地测试