我认为您在某处确实简化了太多。您引用的查询将完全返回您想要的内容。这是一个示例(从单个表中选择两次给出的情况与您所拥有的类似)
mysql> select * from test t1 join test t2 on t1.a = t2.a LIMIT 1,5;+------+------+------+------+| a | b | a | b |+------+------+------+------+| 1 | 2 | 1 | 1 | | 1 | 1 | 1 | 2 | | 1 | 2 | 1 | 2 | | 2 | 2 | 2 | 2 | | 2 | 2 | 2 | 2 | +------+------+------+------+5 rows in set (0.00 sec)
Mysql可以使用相同的标签来标记结果集列。我想您的原始查询在选择部分中选择了t1。*。
如果您要引用名称不明确的单个字段,则会得到
mysql> select a from test t1 join test t2 on t1.a = t2.a LIMIT 1,5;ERROR 1052 (23000): Column 'a' in field list is ambiguous
并且您必须确切指定所需的内容(列别名是可选的,也可以执行t1 ,.t2。 )
mysql> select t1.a first, t2.a second from test t1 join test t2 on t1.a = t2.a LIMIT 1,5;+-------+--------+| first | second |+-------+--------+| 1 | 1 | | 1 | 1 | | 1 | 1 | | 2 | 2 | | 2 | 2 | +-------+--------+5 rows in set (0.00 sec)
编辑22MAR更改示例数据后,您似乎希望将一张表中的几行变成一张。这是一个特殊的解决方案(假设您总是有Tax,Total和Subtotal行,而您只对这些行感兴趣)。
SELECt t1.id, t1.name, t2.product_id, t2.price, t3a.number subtotal, t3b.number total, t3c.number taxFROM `table_one` AS t1 INNER JOIN `table_two` AS t2 ON t1.id = t2.id INNER JOIN `table_three` AS t3a ON t1.id = t3a.id and t3a.text = "Subtotal"INNER JOIN `table_three` AS t3b on t3a.id = t3b.id and t3b.text = "Total"INNER JOIN `table_three` AS t3c on t3b.id = t3c.id and t3c.text = "Tax"
(如果需要,还可以在选择的部分中选择常量“ Tax”,“ Total”和“Subtotal”,并为其指定一些列名称)
尚不清楚的一件事是表中的ID之间的关系-它们是
table_one还是
table_two的主键。当然,当
table_one和table_two中有多行时,这可能会影响结果。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)