搜索SQL语句

时间:2015-08-07 03:15:53

标签: sql

我的表名chat_customer有客户属性:

id, name, status, ...

我还有一个表名chat_friendRelationshipmyId,我的friendId可以在column1或column2中。如何搜索我的所有friendId

我的查询是

SELECT 
    CHAT_CUSTOMER.CUSTOMERID, CHAT_CUSTOMER.CUSTOMERNAME,
    CHAT_CUSTOMER.STATUS, CHAT_CUSTOMER.LASTLOGIN, CHAT_CUSTOMER.ISADMIN
FROM 
    CHAT_CUSTOMER 
LEFT JOIN 
    CHAT_FRIENDRELATIONSHIP ON CHAT_CUSTOMER.CUSTOMERID = CHAT_FRIENDRELATIONSHIP.CUSTOMERID1
                            OR CHAT_CUSTOMER.CUSTOMERID = CHAT_FRIENDRELATIONSHIP.CUSTOMERID2
WHERE 
    CHAT_CUSTOMER.CUSTOMERID = '1';

但它会返回一些包含我的数据的行。我希望它能够返回我的朋友数据。

下面的图片是我的桌子。

chat_customer表:

chat_customer Table

chat_relationship表:

chat_relationship Table

3 个答案:

答案 0 :(得分:2)

有关frinds的详细信息:

select
      c.*
from chat_customer c
inner join (
      select distinct customerid2
      from chat_relationship
      where customerid1 = '1'
      ) friends on c.customerid = friends.customerid2

nb:从示例中不清楚是否需要DISTINCT

仅按ID的朋友列表:

      select distinct customerid2
      from chat_relationship
      where customerid1 = '1'

答案 1 :(得分:2)

另一种编写查询的方法,确定时间更长,但对于我们中的某些人来说可能更容易理解,它会显示costumer_id = 1的朋友的所有数据:

    SELECT   
      CHAT_CUSTOMER.CUSTOMERID  
      CHAT_CUSTOMER.CUSTOMERNAME,  
      CHAT_CUSTOMER.STATUS,  
      CHAT_CUSTOMER.LASTLOGIN,  
      CHAT_CUSTOMER.ISADMIN  
    FROM   
      CHAT_CUSTOMER   
        JOIN CHAT_FRIENDRELATIONSHIP ON 
           CHAT_CUSTOMER.CUSTOMERID = CHAT_FRIENDRELATIONSHIP.CUSTOMERID1
    WHERE
      CHAT_FRIENDRELATIONSHIP.CUSTOMERID2 = 1
    UNION
    SELECT  
      CHAT_CUSTOMER.CUSTOMERID  
      CHAT_CUSTOMER.CUSTOMERNAME,  
      CHAT_CUSTOMER.STATUS,  
      CHAT_CUSTOMER.LASTLOGIN,  
      CHAT_CUSTOMER.ISADMIN  
    FROM
      CHAT_CUSTOMER   
        JOIN CHAT_FRIENDRELATIONSHIP ON 
          CHAT_CUSTOMER.CUSTOMERID = CHAT_FRIENDRELATIONSHIP.CUSTOMERID2
    WHERE 
      CHAT_FRIENDRELATIONSHIP.CUSTOMERID1 = 1
  ;

答案 2 :(得分:1)

以下是获取两次搜索的示例:

select 
c.customerid, 
c.customername, 
c.status,
cr.columnname1,
cr.columnname2,
cr2.columnname1,
cr2.columnname2
from 
chat_customer c
join chat_relationship cr
on c.customerid = cr.customerid1
join chat_relationship cr2
on c.customerid = cr2.customerid2
where c.customer_id = '1';