简体   繁体   English

有条件的2个表中的SQL查询

[英]SQL query from 2 tables with conditions

I am trying to understand how a query from 2 tables linked via one common value is supposed to look like. 我试图了解如何通过一个公共值链接来自2个表的查询看起来像。 Below my example based on the timezone record of my users. 在下面的示例中,根据我的用户的timezone记录。

Table: qci_users (table with all user details) Columns: 表:qci_users(带有所有用户详细信息的表)列:

  • ID ID
  • Timezone 时区

Table: timezones (all GMT timezone information) Columns: 表格:时区(所有GMT时区信息)列:

  • TimeZoneID 时区ID
  • GMTadjustment GMT调整
  • UseDaylightTime UseDaylightTime
  • TimeZone 时区
  • Description 描述

I now would like to query all of the above column values where qci_user.Timezone and timezones.TimeZone have the same value. 我现在想查询以上所有列值,其中qci_user.Timezonetimezones.TimeZone具有相同的值。

Code: 码:

// get user timezone setting
$sql = ("SELECT TimeZoneID, GMTadjustment, UseDaylightTime, TimeZone, Description, qci_users.Timezone
FROM timezones
WHERE qci_users.Timezone = timezones.TimeZone");

$result = $db->query($sql) or die('<p>Query to get timezone data from timezones table failed: ' . mysqli_error($db) . '</p>');

while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
    $id = $row['TimeZoneID'];
    $gmtAdjustment = $row['GMTadjustment'];
    $useDaylightTime = $row['UseDaylightTime'];
    $tz = $row['TimeZone'];
    $description = $row['Description'];
    $user_tz = $row['Timezone'];

    echo "<option timeZoneId=\"$id\" gmtAdjustment=\"$gmtAdjustment\" useDaylightTime=\"$useDaylightTime\" value=\"$user_tz\">$description</option>\n";
}

The query doesnt return any results, hence me wondering where I am going wrong here? 该查询不返回任何结果,因此我想知道我在哪里出错了?

Thanks 谢谢

You are missing a join condition. 您缺少联接条件。 You probably intended this: 您可能打算这样做:

SELECT t1.TimeZoneID,
       t1.GMTadjustment,
       t1.UseDaylightTime,
       t1.TimeZone,
       t1.Description
FROM timezones t1
INNER JOIN qci_users t2
    ON t1.Timezone = t2.TimeZone

Try this 尝试这个

SELECT u.* ,t.* FROM qci_users u LEFT JOIN timezones t ON u.Timezone=t.TimeZoneID 从qci_users中选择u。*,t。* u左联接时区t ON u.Timezone = t.TimeZoneID

This will help you 这对你有帮助

Thanks 谢谢

Try this 尝试这个

SELECT usr.* ,tmz.*
  FROM qci_users AS usr JOIN timezones AS tmz ON usr.Timezone = tmz.TimeZone;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM