gpt4 book ai didi

php - 3个表,左连接,以防ONE表中缺少DATA

转载 作者:行者123 更新时间:2023-11-29 00:58:28 25 4
gpt4 key购买 nike

表1(id一直存在)

+----+------+
| id | col1 |
+----+------+
| 1 | ab |
+----+------+
| 2 | gh |
+----+------+

table2(id一直存在)

+----+------+
| id | col2 |
+----+------+
| 1 | cd |
+----+------+
| 2 | ij |
+----+------+

table3(ids 可能丢失,在这种情况下 2 丢失)

+----+------+
| id | col3 |
+----+------+
| 1 | ef |
+----+------+

PHP

$col = 'ab';

$a = mysql_query("SELECT t1.id FROM table1 AS t1, table2 AS t2, table3 AS t3
WHERE t1.id = t2.id AND t2.id = t3.id AND (t1.col1 = '$col' OR t2.col2 = '$col'
OR t3.col3 = '$col) GROUP BY t1.id, t2.id, t3.id");

这只有在所有三个表都包含“相同的 id”时才有效,但是如果 table3 中由于某种原因缺少“id”会怎样?当 $col = ab 时,我如何仍然测试所有三个表并让 t1.id 输出 1?我必须使用左连接吗?

$a = mysql_query("SELECT t1.id FROM table1 AS t1, table2 AS t2 
LEFT JOIN (SELECT id FROM table3 WHERE col3 = '$col') AS t3 ON t3.id = t1.id
WHERE t1.id = t2.id AND (t1.col1 = '$col' OR t2.col2 = '$col')
GROUP BY t1.id, t2.id");

我做错了什么?

最佳答案

你做错了什么?查询不存在的表。这总是会引发错误。

我不打算讨论设计一个数据库的智慧,在这个数据库中,对您的查询至关重要的表来来去去。

你在客户端的唯一希望是

  • 测试表是否存在你感兴趣,并且
  • 执行不同的SQL语句基于这些结果。


[编辑后]

听起来您需要一个或两个左外连接。这会为您提供 table1 和 table2 共有的所有 ID,无论它们是否在 table3 中。

select t1.id, t2.id, t3.id
from table1 t1
inner join table2 t2 on (t1.id = t2.id)
left join table3 t3 on (t1.id = t3.id);

这会为您提供表 1 中的所有 ID,无论它们是在表 2 中还是表 3 中。

select t1.id, t2.id, t3.id
from table1 t1
left join table2 t2 on (t1.id = t2.id)
left join table3 t3 on (t1.id = t3.id);

当然,您可以使用 WHERE 子句过滤结果。

关于php - 3个表,左连接,以防ONE表中缺少DATA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4921378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com