左外连接错误导致MYSQL

时间:2016-02-02 07:12:15

标签: php mysql join

我正在使用MySQL连接。我有两张桌子需要加入。第一个表包含所有房地产属性,第二个表包含向该属性添加收藏夹的用户。现在我想要为登录用户显示所有带有收藏夹图标的属性。我在MySQL中编写以下查询。但是这个查询会返回所有记录。

  NSURL *URL = [[NSBundle mainBundle] URLForResource:@"sample" withExtension:@"pdf"];

if (URL) {
    // Initialize Document Interaction Controller
    self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:URL];

    // Configure Document Interaction Controller
    [self.documentInteractionController setDelegate:self];

    // Preview PDF
    [self.documentInteractionController presentPreviewAnimated:YES];
}

还有一个问题。如果多个用户在收藏夹

中添加相同的属性,则此查询会返回重复属性

这是我在使用此查询时从api获得的最终输出

SELECT a. * , b.property_id AS fav, b.user_id
FROM `property_for_sale` a
LEFT OUTER JOIN `cpo_favourite_property` b ON a.id = b.property_id
WHERE a.property_type = 'Commercial'
UNION
SELECT a. * , b.property_id AS fav, b.user_id
FROM `property_for_rent` a
LEFT OUTER JOIN `cpo_favourite_property` b ON a.id = b.property_id
WHERE a.property_type = 'Commercial'
ORDER BY id DESC

2 个答案:

答案 0 :(得分:0)

我认为您对当前登录的用户缺少限制。将其添加到log4j2.xml子句(<?xml version="1.0" encoding="UTF-8"?> <Configuration> <Appenders> <File name="A1" fileName="A1.log" append="false"> <PatternLayout pattern="%t %-5p %c{2} - %m%n"/> </File> <Console name="STDOUT" target="SYSTEM_OUT"> <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/> </Console> </Appenders> <Loggers> <Logger name="org.apache.log4j.xml" level="debug"> <AppenderRef ref="A1"/> </Logger> <Root level="warn"> <AppenderRef ref="STDOUT"/> </Root> </Loggers> </Configuration> 占位符):

    <?xml version="1.0" encoding="UTF-8"?>
<Configuration>
  <Appenders>
    <File name="A1" fileName="A1.log" append="false">
      <PatternLayout pattern="%t %-5p %c{2} - %m%n"/>
    </File>
    <Console name="STDOUT" target="SYSTEM_OUT">
      <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
    </Console>
  </Appenders>
  <Loggers>
    <Logger name="org.apache.log4j.xml" level="debug">
      <AppenderRef ref="A1"/>
    </Logger>
    <Root level="info">
      <AppenderRef ref="A1"/>
    </Root>
  </Loggers>
</Configuration>

答案 1 :(得分:0)

如果您想要显示两个用户,请使用以下查询 -

SELECT a. * , b.property_id AS fav, group_concat(b.user_id)
FROM `property_for_sale` a
LEFT OUTER JOIN `cpo_favourite_property` b ON a.id = b.property_id
WHERE a.property_type = 'Commercial'
group by a.id
UNION
SELECT a. * , b.property_id AS fav, group_concat(b.user_id)
FROM `property_for_rent` a
LEFT OUTER JOIN `cpo_favourite_property` b ON a.id = b.property_id
WHERE a.property_type = 'Commercial'
group by a.id
ORDER BY id DESC

注意:如果您不想显示多个逗号分隔用户,请不要使用group_concat函数,那么您的查询只会为您提供第一个用户。