1

我有一张tbl_customers桌子。(像许多人一样)

我有第二张桌子: tbl_customers_tags

这张表只是让我为单个客户记录存储无限的关键字/标签。这是列结构:

`tbl_customers_tags`

+-------------+---------------------+------+-----+---------+----------------+
| Field       | Type                | Null | Key | Default | Extra          |
+-------------+---------------------+------+-----+---------+----------------+
| ID          | int(11) unsigned    | NO   | PRI | NULL    | auto_increment |
| customerid  | int(11) unsigned    | NO   | MUL | NULL    |                |
| tagid       | mediumint(5)unsigned| NO   |     | NULL    |                |

因此,我现在需要通过查找具有特定 tagid 的任何客户记录来提取一些报告。我得到重复。这是我当前的查询语句:

SELECT  c.firstname, c.lastname, c.datecreated  
FROM `tbl_customers` c 
LEFT JOIN `tbl_customers_tags` ctags ON c.customerid = ctags.customerid 
WHERE ctags.tagid IN(2,3,15) 

当单个记录customerid与多个tagid记录相关联时,有没有办法不返回重复项?

4

3 回答 3

0

尝试这个

SELECT  c.firstname, c.lastname, c.datecreated  
FROM 'tbl_customers' c 
where exists
( select 'x' from tbl_customers_tags where customerid = c.customerid and
tagid IN(2,3,15)
) 

如果您只对在标签表中有记录的客户感兴趣,为什么不进行完全连接而不是左连接呢?

于 2013-01-06T19:12:45.497 回答
0
SELECT  distinct c.firstname, c.lastname, c.datecreated  
FROM `tbl_customers` c 
LEFT JOIN `tbl_customers_tags` ctags ON c.customerid = ctags.customerid 
WHERE ctags.tagid IN(2,3,15) 
于 2013-01-06T19:00:56.643 回答
0

如果你真的不关心重复,你可以使用DISTINCT关键字。此外,您不需要执行 a ,LEFT OUTER JOIN因为您有一个WHERE依赖于另一个表的子句。像这样的东西:

SELECT  DISTINCT c.firstname, c.lastname, c.datecreated  
FROM `tbl_customers` c 
JOIN `tbl_customers_tags` ctags 
ON c.customerid = ctags.customerid 
WHERE ctags.tagid IN (2,3,15) 
于 2013-01-06T19:02:55.953 回答