Php MySQL查询返回重复项

Php MySQL查询返回重复项,php,mysql,sql,Php,Mysql,Sql,我对SQL非常陌生 当我执行以下查询时,它返回以下结果: SELECT table1.image_name, table1.item_id FROM table1, table2, table3 WHERE table2.catagory="item" AND table3.account_id=59 image_name image_id ------------------------- d9.jpg 89 d9.jpg 89 d9.jpg 89 d9.

我对SQL非常陌生

当我执行以下查询时,它返回以下结果:

SELECT table1.image_name, table1.item_id
FROM table1, table2, table3
WHERE table2.catagory="item"
AND table3.account_id=59

image_name    image_id
-------------------------
d9.jpg      89
d9.jpg      89
d9.jpg      89
d9.jpg      89
d10.jpg      90
d10.jpg      90
d10.jpg      90
d10.jpg      90
etc.....
结果重复相同属性四次!我不明白这是为什么,我在任何地方都找不到原因

我有3个表,表1 PK(image_id)被引用为项目中的FK。表3中的FK引用了项目PK(项目id)。表3有一个来自表4(帐户id)和表2(项目id)的复合键

我的问题显然是错的,但我不明白为什么?我希望有人能解释一下结果!,或者帮我指出正确的方向


谢谢

在这种情况下,您需要使用
DISTINCT
,因为您有多行匹配相同的信息:

SELECT DISTINCT table1.image_name, table1.item_id 
FROM table1, table2, table3 
WHERE table2.catagory="item" 
AND table3.account_id=59
但是,正如其他人提到的,您需要指定连接正在使用的表的条件,例如:

SELECT DISTINCT table1.image_name, table1.item_id 
FROM table1 
JOIN table2 on table2.item_id = table1.item_id
JOIN table3 on table3.item_id = table1.item_id
WHERE table2.catagory="item" 
AND table3.account_id=59
或:


您列出了3个表,并且只连接了其中的两个表。
这意味着您将从联接中获得一行,并且它将对第三个表中的每一行重复一次(在本例中为表1)

从表1、表2、表3中选择不同的表1.image\u name、表1.item\u id,其中表2.catagory=“item”和表3.account\u id=59

虽然这更像是一个解决办法


如果您可以更清楚地指定表的结构,这将很有帮助

也许我误解了这个问题,但是除了如上面海报所建议的那样添加“Distinct”,我认为您还需要在Where子句中添加表3和表2之间的关系。根据你所描述的,我认为下面这样的方法会奏效。根据表的实际结构,可能需要一些附加条件

SELECT DISTINCT table1.image_name, table1.item_id 
FROM table1, table2, table3 
WHERE    table2.catagory="item"
 AND table3.account_id=59 
 AND table3.item_id = table2.item_id

由于未指定联接条件,因此会得到多个结果。外键关系良好,但需要指定它们在查询中应用:

SELECT table1.image_name, table1.item_id
FROM table1, table2, table3
WHERE table2.catagory="item"
AND table3.account_id=59
AND table1.id = table2.item_id
AND table2.item_id = table3.id

注意最后两个条件。您需要更改它们以满足您的需要。

您必须明确说明连接条件-否则您将得到所有项目的所有3个表的笛卡尔积59

where table1.image_id = table2.item_id
and table2.item_id = table3.item_id
and ...

可能有一些列您没有选择,这将使行看起来唯一。因此,可能您的查询工作正常,但是,由于您没有选择所有的列,它们显示为重复的行。

查询是否在PHP中运行?如果是这样的话,请给我们看看你的代码。我仔细阅读后发现,你实际上甚至没有加入任何东西。。。你应该有一部分WHERE子句链接表,如和table1.id=table2.id等@achusonline、Randy、darkajax和juergen,aelfric感谢大家的解释,我如何才能投票给大家!!!谢谢Arjan的建议!你救了我一天。非常感谢。
where table1.image_id = table2.item_id
and table2.item_id = table3.item_id
and ...