doubiao9775 2015-07-20 04:51
浏览 67

从table1中选择3个值并使用table2中table1中的一个值来获取结果?

Hi Stackoverflow members!

I got this dilemma:

users  ID  username  firstname  middlename lastname
        1  bilbodog    Casper               Thomsen
        2  bilbodog2   Smith      John      Andersen


flirts    flirter_id  flirted_id  date  time
              1          2          X    X

I wanna get all the flirted_id's made by the flirter_id '1' and compare the flirted_id to users and gather the firstname, middlename & lastname from the flirted_id. Plus I wanna gather the date and time from the flirts table. Then I wanna echo the results out in a HTML table.

So for now I am doing this:

<?php
$ID=$_SESSION['ID'];
// Create connection
$conn = new mysqli($mysql_hostname, $mysql_user, $mysql_password, $mysql_database);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT flirted_id, date, time FROM flirts WHERE flirter_id='$ID'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
  ----> ECHO TABLE <----
} else {
  echo 'No flirts found.';
}
$conn->close();
?>

But that does not work.

I am so stuck at this point. I dunno how to gather 3 results from 1 table and use one of the results to compare at table 2, to gather the firstname, middlename and lastname of the person that goes by that ID.

  • Thanks in advance!
</div>
  • 写回答

3条回答 默认 最新

  • duanhunlou7051 2015-07-20 05:01
    关注

    If I understand you correctly you want to do a join to grab the information from table1 and also the information about the person in table 2 who is listed as added_id in table1

    select t1.date, t1.time, t2.first, t2.middle, t2.last
    from table1 t1
    join table2 t2 on (t1.added_id = t2.id)
    where t1.adder_id = 1;
    

    If you also want the information about the adder_id (assuming the persons are also stored in table2):

    select t1.date, t1.time, t2.first, t2.middle. t2.last, t3.first, t3.middle, t3.last
    from table1 t1
    join table2 t2 on (t1.added_id = t2.id)
    join table2 t3 on (t1.added_id = t3.id)
    where t1.adder_id = 1;    
    

    In this case you should give the person cols alias to identify them more cleary, e.g. t2.first as added_id_first, t3.first as adder_id_first and so on

    Note I assume that there are no NULL values in the adder_id and added_id fields. If they can then use a LEFT JOIN instead of JOIN in the statements.

    评论

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)