One variable row inside another variable row

前端 未结 3 1843
庸人自扰
庸人自扰 2021-01-28 16:09

I have following script:

$sql = \"SELECT * FROM `users`\"
$q = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($q);
$sql1 = \"SELECT * FROM `ot         


        
相关标签:
3条回答
  • 2021-01-28 16:48

    Guess you want something like

    SELECT * FROM table1 t1, table2 t2 WHERE t1.user_name = t2.user_name?
    

    Think about using JOIN

    0 讨论(0)
  • 2021-01-28 16:53
    SELECT * FROM users AS u INNER JOIN other_table AS o ON u.username = o.username
    

    I'm assuming you want to do this because you want to be able to access all the rows from either table where a particular user name is the same (e.g. the data from users where username="john" and the data from other_table where username="john" for all usernames). No need to nest a result set to do this, just use a JOIN statement and then you can access all the columns as if it was a single result set (because it is):

    $sql = "SELECT * FROM users AS u INNER JOIN other_table AS o ON u.username = o.username";
    $q = mysql_query($sql) or die(mysql_error());
    $row = mysql_fetch_array($q);
    
    $item = $row['any_column'];
    

    FYI you should list out the column you want to retrieve instead of using *, even if you want to retrieve them all, as it is better practice in case you add new columns in the future.

    0 讨论(0)
  • 2021-01-28 16:58
    $sql = "SELECT * FROM users;";
    $q = mysql_query($sql) or die(mysql_error());
    $row = mysql_fetch_array($q);
    
    $sql1 = sprintf("SELECT * FROM other_table where username='%s';", $row['username']);
    $q1 = mysql_query($sql1) or die(mysql_error());
    $row1 = mysql_fetch_array($q1);
    

    // now $row1 contains the tuple of this user and could access the variables are you would // normally do e.g. $row1['ID']

    0 讨论(0)
提交回复
热议问题