Php 如何检查多个表中是否存在类似值

Php 如何检查多个表中是否存在类似值,php,mysql,database,Php,Mysql,Database,我已经在这里(和其他地方)阅读和评论了很多关于如何做到这一点的帖子,但我的研究结果似乎是从有意义的方面倒退过来的 我有4个表具有不同的列/数据,但我需要从中选择的列是相同的,并且具有相同的结构 Table 1: | id | item_id | user | other table 1 specific columns...<br> Table 2: | id | item_id | user | other table 2 specific columns...<br>

我已经在这里(和其他地方)阅读和评论了很多关于如何做到这一点的帖子,但我的研究结果似乎是从有意义的方面倒退过来的

我有4个表具有不同的列/数据,但我需要从中选择的列是相同的,并且具有相同的结构

Table 1: | id | item_id | user | other table 1 specific columns...<br>
Table 2: | id | item_id | user | other table 2 specific columns...<br>
Table 3: | id | item_id | user | other table 3 specific columns...<br>
Table 4: | id | item_id | user | other table 4 specific columns...<br>
所以,我希望看到的是表1中的一个空结果和表2中的一个带有项目_id的结果,但实际情况是,我从表2中没有得到任何结果,从表1中得到一个“命中”

由于表1实际上并没有包含item_id=35和user='usernamehere'的记录,因此看起来有些倒退和混乱


非常感谢您的建议或见解。

您的查询只是在特定表中列出了
项目id
。它没有具体说明它们来自哪里。对于两个表,可以使用
join
解决问题

我想更多的桌子,你会想要这样的东西:

select item_id, group_concat(which order by which) as tables
from ((select item_id, user, 'table1' as which from table1) union all
      (select item_id, user, 'table2' from table1) union all
      (select item_id, user, 'table3' from table1) union all
      (select item_id, user, 'table4' from table1)
     ) t
where user = 'usernamehere'
group by item_id;
对于每个
项目_id
,这将列出它所在的表。如果您希望在所有四个表中都包含项目。然后添加一个
having
子句:

having count(distinct which) = 4;
类似地,如果您想要缺少一个或多个示例:

having count(distinct which) < 4;
具有计数(不同的)<4;

假设$var有您的搜索字段:

select
    inp.ID,
    count(t1.itemID) as TableOne,
    count(t2.itemID) as TableTwo,
    count(t2.itemID) as TableThree,
    count(t3.itemID) as TableFour
from
    (
        select
            ".$var." as ID
        from
            dual
    ) inp
    left outer join
        table1 t1
            on inp.ID=t1.item_id
    left outer join
        table2 t2
            on inp.ID=t1.item_id
    left outer join
        table3 t3
            on inp.ID=t1.item_id
    left outer join
        table4 t4
            on inp.ID=t1.item_id
group by
    inp.ID
这将通过选择您创建的表和与其他表的外部联接(您可以很好地计算)来计算项目是否在您的表中。

UNION将合并结果(行),我认为这不是您需要的

考虑使用JOIN语句:

SELECT exTable.ID

FROM exTable as t1

JOIN t2 as t2 ON t1.col = t2.col // we have value of col in t2 same as in t1
JOIN t3 as t3 ON t1.col = t3.col 
JOIN t4 as t4 ON t1.col = t4.col

WHERE t1.ID = 35 AND t1.user = 'usernamehere'

在某些情况下,您可能会使用左连接或右连接,您可以在W3C上阅读有关它们的信息。

谢谢Gordon-您的解决方案非常有效,为我节省了大量时间!!!非常感谢!
SELECT exTable.ID

FROM exTable as t1

JOIN t2 as t2 ON t1.col = t2.col // we have value of col in t2 same as in t1
JOIN t3 as t3 ON t1.col = t3.col 
JOIN t4 as t4 ON t1.col = t4.col

WHERE t1.ID = 35 AND t1.user = 'usernamehere'