Select multiple values from multiple rows - mysql

Cant figure out how to get this result:
ProductID Variantno
53121 5197, 5198,5199
From this data collection.
ProductID Variantno
53121 5197
53121 5198
53121 5199
Tried with group by but no good result, total sql noob...

Try this..
SELECT
ProductID,
GROUP_CONCAT(Variantno)
FROM tbl
GROUP BY ProductID

select ProductID , group_concat(Variantno)
from table
group by ProductID

Try this:
WITH cte AS (
SELECT
ProductID,
CAST('<r>' + REPLACE(variantNo, ',', '</r><r>') + '</r>' AS XML) AS VariantNos
FROM TestTable
)
SELECT
ProductID,
xTable.xColumn.value('.', 'VARCHAR(MAX)') AS VariantNo
FROM cte
CROSS APPLY VariantNos.nodes('//r') AS xTable(xColumn)

Without showing your code and database. I assumed that you are working with php and mysql.
I have run and tested this code and it works. that means it will work for you. my connection is PDO. Give me a shout if are still having issues
<?php
// pdo connection
$db = new PDO (
'mysql:host=localhost;dbname=sectona_db;charset=utf8',
'root', // username
'root90' // password
);
?>
<?php
Echo 'Data Output:<br>';
include("pdo.php");
$result = $db->prepare("SELECT * FROM product where id='123'");
$result->execute(array());
while ($r = $result->fetch())
{
//$data = htmlentities($r['product'], ENT_QUOTES, "UTF-8");
?>
<?php echo htmlentities($r['product'], ENT_QUOTES, "UTF-8");?>,
<?php } ?>

Related

to find a value within the array in mysql

i want to search data in an array .How can i search using mysql select command. i wrote the query as
$this->db->query("SELECT * FROM client_details WHERE dob IN ({implode(',', $data})");
$data is an array of dates .Please Help me for solving this..
try with
$data =array('0'=>'2015-01-23','1'=>'2015-01-22','2'=>'2015-01-21');
$tmp = implode('","', $data);
$tmp ='"'.$tmp.'"';
$sql= 'SELECT * FROM client_details WHERE dob IN ('.$tmp.')';
echo $sql;
$this->db->query($sql);
You can do something like this:
Option 1
$tmp = implode(',', $data);
$this->db->query("SELECT * FROM client_details WHERE dob IN ($tmp)");
Option 2
$this->db->query("SELECT * FROM client_details WHERE dob IN (".implode(',', $data).")");
Also, there is a mistake in your bracket formation.
It should be dob IN ({implode(',', $data)}"); [Curly braces should close after the closing parenthesis].

CanĀ“t retrieve the date from MySQL

I do an INSERT into mySQL database like this:
$sDate=date("Y-m-d h:i:s");
INSERT INTO tbl_1 (datum) VALUES ('$sDate')
And it'll do the INSERT
But then when I try to find out the unique ID by selecting the date like this:
SELECT id AS nyPost FROM tbl_1 WHERE datum ='$sDate'
It will return nothing, not even an error message. The datum format is datetime.
Please whats wrong?
CODE:
<?php
$sDate=date("Y-m-d h:i:s");
echo $sDate;
If ($strNy)
{
$_nyPrSQL="INSERT INTO begagnads (`anvId`, `tabort`, `datum`) VALUES ('8' , 'null', '$sDate')";
// echo $_nyPrSQL;
if (!mysqli_query($con,$_nyPrSQL))
{die('Error: ' . mysqli_error($con));}
else
{
echo "<br>1 record added";
}
$result = mysqli_query($con,"SELECT id FROM begagnads WHERE DATE(datum) ='$sDate' ");
while($row = mysqli_fetch_array($result)) {
echo $row['id'] . " " . $row['datum'];
$nyPost= $row['id'];
echo "<br>";
}
?>
MySql DATE() function Extracts the date part of the date or datetime expression expr.
mysql> SELECT DATE('2003-12-31 01:02:03');
-> '2003-12-31'
If you want to find by DATE only
SELECT id FROM begagnads WHERE DATE(datum) = DATE('$sDate')
And if you find with date and time then no need DATE() function
SELECT id FROM begagnads WHERE datum = '$sDate'
You need this:
INSERT INTO tbl_1 (datum) VALUES ($sDate)
Try looking at your table named tbl_1 after the above, by using:
SELECT * FROM tbl_1

MySQL query optimization in codeigniter

I have function in CodeIgniter to retrieve latest posts from 2 tables:
public function get_latest_comments($amount)
{
$query = $this->db->query('
SELECT *, FROM_UNIXTIME(date) AS timestamp
FROM comments
ORDER BY timestamp DESC
LIMIT 5
');
if ($query->num_rows() > 0) {
$result = $query->result_array();
for ($i = 0; $i < sizeof( $result ); $i++) {
$result[$i]['author_info'] = $this->comments_model->get_comment_author( $result[$i]['id'] );
$result[$i]['date'] = mdate( "%M %m, %Y", $result[$i]['date'] );
if ($result[$i]['section'] === 'blog') $loc = 'blog_posts';
if ($result[$i]['section'] === 'core') $loc = 'public_posts';
$this->db->select( 'title, slug' );
$query = $this->db->get_where( $loc, array('id' => $result[$i]['location']) );
$result[$i]['post_title'] = $query->row( 'title' );
$result[$i]['url'] = base_url() . $result[$i]['section'] . '/view/' . $query->row( 'slug' ) . '/';
}
return $result;
}
return false;
}
The problem is that it runs too slow. My page sometimes loads 7-8 seconds. I suspect this query running 2 times + similar query gathering latest comments slows down my page.
I have a bad feeling about queries inside the loop. How can I avoid that?
The structure of my table is:
users (id, username, mail ...
user_info ( user_id, name, surname
public_posts ( id, slug, text, author(user id) ...
blog_posts ( id, slug, text ...
comments ( id, text, author, location(post_id_, section(post_table) ...
Check by expalining your Query , Go to the mysql command line and type
EXPLAIN SELECT *, FROM_UNIXTIME(date) AS timestamp FROM comments ORDER BY timestamp DESC LIMIT 5
Explain will tell you everything about the query, On its bases you can decide for the indexing also.
Make a practice to expalin every select query before using it in the code.
Plus you can also do profiling when ever you think your code is taking time. In codeigniter Profiler class is available, please go through the below link.
https://www.codeigniter.com/userguide3/general/profiling.html

Better way to do this MySQL query?

This is what I'm doing now, how to do this without resorting to a subquery and without the php. I can just run it inside phpmyadmin directly:
<?php
$query = mysql_query(" SELECT node_id FROM embeds ");
while($row = mysql_fetch_assoc($query)) {
$node_id = $row['node_id'];
mysql_query(" INSERT INTO node_teaser(node_id, content) VALUES('$node_id', 'This is the teaser!') ");
}
?>
INSERT INTO node_teaser(node_id, content)
SELECT node_id, 'This is the teaser!' FROM embeds;

Mysql and php - compare them and bring back one out of the two values

Category Make
BUS hiace
Car honda
bus hiace
Expected Result:
bus (hiace) - in the drop down list
car (honda) - in a different drop down list
<SCRIPT TYPE="TEXT/JAVASCRIPT">
function setup(ans) {
lit = ''
if (ans == 'bus') {
<?php
$result = mysql_query("select Category from auto
group by Make"); ?>
lit = lit+ '<select name="q4" ONCHANGE="alert(document.quest.q4.value)" style="width:130px; background-color:#FFCC33; font-weight:bold; font-size:12px;" >'
lit = lit+ '<option>MAKE</option>'
<?php while($row = mysql_fetch_array($result))
{
$make = $row['Make'];
//print $make;
?>
var make = "<?php echo $make; ?>"
lit = lit+ '<option>'+make+'</option>'
<?php }?>
lit = lit+ '</select>'
}
</script>
For a random ID of the ones matching, try
SELECT * FROM table_name GROUP BY Name;
or if you want the maximum ID with the same name
SELECT MAX(ID),Name FROM table_name GROUP BY name;
This naturally works with MIN() too if you want the first ID.
SELECT id,name FROM tbl_names GROUP BY name ORDER BY id ASC ?
select min(ID), Name
from tablename
group by Name
SELECT *
FROM table
GROUP BY Name
SELECT *
FROM table
where ID IN (select MIN(ID)
FROM table
GROUP BY Name)