0

我需要解决一个关于基于字段连接表的问题。我有 3 张桌子:

NEWS (id,title)

COMMENTS (id,idtopic,message)

NOTIFICATIONS (iduser,idnews,idtopic,idpost)

COMMENTShasidtopic=0时为主题,>0 时为主题回复。由NOTIFICATIONS用户了解各种信息。

现在我想从其他表中获取字段,选择NOTIFICATIONS.

基础SELECT是:

SELECT idnews,idtopic,idpost FROM notifications WHERE iduser=X

现在我想加入:

  • NEWS->标题,如果 idnews>0
  • COMMENTS->message,如果 idtopic>0
  • COMMENTS->message,如果 idpost>0

我想我应该做这样的事情:

SELECT CASE idnews>0 THEN ??,
       CASE idtopic>0 THEN ??, CASE idpost>0 THEN
  FROM NOTIFICATIONS

我想总是返回一个带有标题或消息的字段,因为 idnews/idtopic/idpost 之一总是 >0

如何在不加入每条记录的每个表的情况下在 SELECT 中选择?我不想做

SELECT *
 FROM NOTIFICATIONS
 LEFT JOIN NEWS ON NOTIFICATIONS.idnews=NEWS.id
 LEFT JOIN COMMENTS ON NOTIFICATIONS.idtopic=COMMENTS.id
 LEFT JOIN COMMENTS ON NOTIFICATIONS.idpost=COMMENTS.id

因为性能会比to差CASE WHEN idnews>0 OR idtopic>0 OR idpost>0

4

2 回答 2

0

我不知道这是否是您的要求,但是,您可以在这样的选择中进行选择...

SELECT donor.idno, name, contamt, driveno 
FROM donor, donation 
WHERE donor.idno = donation.idno AND driveno > any 
(SELECT driveno FROM drive WHERE drivename = 'Animal Home');
于 2013-02-08T11:25:26.233 回答
0

我希望我理解正确,试试这个:

create procedure printNotification(in input_userid int)
BEGIN
  DECLARE id_news int;
  DECLARE id_topic int;
  DECLARE id_post int;
  DECLARE id_title char(30);
  DECLARE id_message char(30);
  SELECT idnews,idtopic,idpost INTO @id_news,@id_topic,@id_post FROM NOTIFICATIONS WHERE iduser=input_userid;
  IF(id_news>0) THEN
    SELECT title INTO @id_title FROM NEWS WHERE id=id_news;
  END IF;

  IF(id_topic>0) THEN
    SELECT message INTO @id_message FROM COMMENTS WHERE id=idtopic;
  END IF;

  IF(idpost>0) THEN
    SELECT message INTO @id_message FROM COMMENTS WHERE id=idpost;
  END IF;

END//
于 2013-02-08T13:50:46.653 回答