简体   繁体   中英

How to join table and display it?

I tried to combine 2 tables.

Example, table A and B.

  • Table A have 2 columns (id and value)
  • Table A have 3 rows (1, a), (1, b) and (1, c).
  • Table B have 1 column and 1 row (id) is (1)

I have tried to do it with join table , results: 3 rows id and value is (1, a), (1, b), (1, c)

Its not what i want, i need to create like:

Results:

Only 1 row, id is (1) and value is (a, b, c)

But , i just want to get "c" data from "value".

So , the result that I want is (1, c), and how?

Edit:

Check, theres work: http://sqlfiddle.com/#!9/b0fd3b/2

Its not work on my code, resluts is not found. Check this:

<?php
if (isset($_GET['page_no']) && $_GET['page_no']!="") {
  $page_no = $_GET['page_no'];
}
else {
  $page_no = 1;
}
$total_records_per_page = 3;
$offset = ($page_no-1) * $total_records_per_page;
$previous_page = $page_no - 1;
$next_page = $page_no + 1;
$adjacents = "2"; 
$result_count = mysqli_query($conn, "SELECT COUNT(*) As total_records FROM b");
$total_records = mysqli_fetch_array($result_count);
$total_records = $total_records['total_records'];
  $total_no_of_pages = ceil($total_records / $total_records_per_page);
$second_last = $total_no_of_pages - 1; // total page minus 1
$result = mysqli_query($conn, "SELECT id, a.meta_key, a.meta_value FROM a JOIN b USING (id) WHERE a.meta_value = 'value2' LIMIT $offset, $total_records_per_page");
if (mysqli_num_rows($result) > 0) {
  while ($row = mysqli_fetch_array($result)) {
    echo $row['id'];
    echo $row['key'];
    echo $row['value'];
  }
}
else {
  echo "no found";
}
?>
// pagination
....

You could do something like:

select a.*
from a join
     b
     on a.id = b.id
order by a.value desc
limit 1;

I'm a bit confused on why a join is needed at all:

select a.*
from a
order by value desc
limit 1;

But you seem to want the join .

Try the query below. I hope it will get the result that you want.

SELECT a.id, a.value, 
FROM a
INNER JOIN b ON a.id=b.id; 
ORDER BY
    a.id DESC;

Only 1 row, id is (1) and value is (a, b, c)

SELECT id, GROUP_CONCAT(value ORDER BY value) values
FROM a
JOIN b USING (id)
GROUP BY id

But, i just want to get "c" data from "value".

SELECT id, a.value
FROM a
JOIN b USING (id)
WHERE a.value = 'c'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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