如何在有限制的2个表之间创建选择联接

时间:2017-03-03 00:48:05

标签: mysql sql

英语不是我的母语,所以我提前为错误道歉...

好吧,我有3个MySQL表:

# Your database
mydb:
  image: mysql
  ports:
    - "3306:3306"
  volumes:
    - yourDataDir:/var/lib/mysql

# Your server
myserver:
  image: myserver
  ports:
    - "....:...."
  entrypoint: ./wait-for-it.sh mydb:3306 -- ./yourEntryPoint.sh

我需要列出来自特定用户的所有来电,并通过电话号码与他们的联系人联系。这是我到目前为止所得到的:

users:
- Id    INT 11
- Name  VARCHAR 30

calls:
- Id         INT 11
- UserId     INT 11
- DateBegin  DATETIME
- DateEnd    DATETIME
- Phone      VARCHAR 30

contacts:
- Id      INT 11
- UserId  INT 11
- Name    VARCHAR 40
- Phone1  VARCHAR 30
- Phone2  VARCHAR 30

Relationship:
1 user -> many calls (users.Id - calls.UserId)
1 user -> many contacts (users.Id - contacts.UserId)

此代码存在2个问题我无法解决:

  1. 它仅列出与联系人相关的呼叫。如果我删除了WHERE子句中的“AND contacts.UserId = 1”,它可以工作,但来自其他用户的联系人在联接中是相关的;

  2. 有时电话号码是空字符串,因此首先与空号码联系并创建连接。当call.phone为空时,我需要它忽略联系。

  3. 拜托,有些SQL专家可以帮帮我吗?谢谢!

2 个答案:

答案 0 :(得分:3)

second 表中的条件应该在on子句中:

SELECT c.Id, c.DateBegin, c.DateEnd, c.Phone, MAX(co.Name) as Name
FROM calls c LEFT JOIN
     contacts co
     ON (RIGHT(c.Number, 8) = RIGHT(co.Phone1, 8) OR
         RIGHT(c.Number, 8) = RIGHT(co.Phone2, 8)
        ) AND co.UserId = 1 
WHERE c.UserId = 1
GROUP BY c.Id
ORDER BY c.DateBegin DESC;

答案 1 :(得分:0)

通过对条件进行分组并在ID上进行匹配,然后提供特定的id:

来尝试相等的连接
SELECT
    ca.ID
    ca.DateBegin,
    ca.DateEnd,
    ca.Phone,
    contacts.Name
FROM
    calls ca , contacts co 
Where
    calls.Id = contacts.UserId
    AND(
        RIGHT(ca.Number, 8) = RIGHT(co.Phone1, 8) OR
        RIGHT(ca.Number, 8) = RIGHT(co.Phone2, 8) )
AND
    ca.UserId = 1
AND 
   (ca.Phone is not null OR ca.Phone != " ")
GROUP BY
    ca.Id
ORDER BY
    ca.DateBegin DESC;