I have this 3 sql questions:
$producent = mysql_fetch_array(mysql_query("
SELECT FieldValue
FROM `xy8vx_rsform_submission_values`
WHERE SubmissionId = '$id' AND FieldName = 'Producent'
"));
$model = mysql_fetch_array(mysql_query("
SELECT FieldValue
FROM `xy8vx_rsform_submission_values`
WHERE SubmissionId = '$id' AND FieldName = 'Model'
"));
$nr_ser= mysql_fetch_array(mysql_query("
SELECT FieldValue
FROM `xy8vx_rsform_submission_values`
WHERE SubmissionId = '$id' AND FieldName = 'Nr seryjny'
"));
Is it posible to get those 3 values with one sql question?
Yes, use IN clause.
SELECT FieldName , FieldValue
FROM `xy8vx_rsform_submission_values`
WHERE SubmissionId = '$id' AND FieldName IN ('Producent', 'Model', 'Nr seryjny')
And of course you need to use a loop to fetch the result.
// $sql is the above sql
$res = mysql_query($sql);
$result = array();
while ($row = mysql_fetch_assoc($res)) {
$result[$row['FieldName']] = $row['FieldValue'];
}
print_r($result);
To fetch the 3 values in 3 rows:
SELECT FieldValue
FROM `xy8vx_rsform_submission_values`
WHERE SubmissionId = '$id' AND
FieldName in ('Producent', 'Model', 'Nr seryjny')
or, to fetch the 3 values in 3 columns:
SELECT
(SELECT FieldValue
FROM `xy8vx_rsform_submission_values`
WHERE SubmissionId = '$id' AND FieldName = 'Producent') as Producent,
(SELECT FieldValue
FROM `xy8vx_rsform_submission_values`
WHERE SubmissionId = '$id' AND FieldName = 'Model') as Model,
(SELECT FieldValue
FROM `xy8vx_rsform_submission_values`
WHERE SubmissionId = '$id' AND FieldName = 'Nr seryjny') as NrSeryjny
Learn to and use the SQL IN operator.
$id_1=x;
$id_2=y;
$id_3=z;
$name_1="NAME X";
$name_2="NAME Y";
$name_3="NAME Z";
SELECT FieldValue
FROM `xy8vx_rsform_submission_values`
WHERE ((SubmissionId = $id_1 AND FieldName = $name_1) or (SubmissionId = $id_2 AND FieldName = $name_2) or (SubmissionId = $id_3 AND FieldName = $name_3));
Now, you have to fetch your result into an array of 3 rows.
a single query will produce result of these 3 query
$producent = mysql_fetch_array(mysql_query("
SELECT FieldValue
FROM `xy8vx_rsform_submission_values`
WHERE SubmissionId = '$id' AND (FieldName = 'Producent' OR FieldName = 'Model' OR FieldName = 'Nr seryjny')
"));
Related
I have 2 tables. The first one is messages and the second is room. msg_id from messages table is the same as id from room table. What I'm doing is selecting all msg_id and for each of them I wanna run a query that deletes all rooms that their ids dont match with msg_id:
My code:
$result = mysql_query("SELECT `msg_id` FROM `messages`");
while($row = mysql_fetch_array( $result )) {
$me = $row[0]; //$me as a string
$int = (int)$me;//transform $me's value to int
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT LIKE '%" . $int . "%'");}
The $result2 query will delete all entries from room table, no matter the value of $int variable. That means that the check is not working. If I change the $result2 to this i.e.:
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT LIKE '%86%'");
all entries will be Deleted except the room entry with id = 86 (it works fine)
The basic plan is that I must keep all room entries that match their id with msg_id .
DELETE FROM `room` WHERE `id` NOT IN (SELECT `msg_id` FROM `messages`)
if you can't use subquery you can try:
$result = mysql_query("SELECT `msg_id` FROM `messages`");
$ids = [];
while($row = mysql_fetch_array($result)) {
$ids[] = (int) $row[0];
}
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT IN (" . implode(',', $ids) . "));
and PLS don't USE mysql_query it is DEPRECATED
Could you use a subquery?
DELETE FROM ROOM WHERE id not in(SELECT msg_id FROM messages);
Try this query,
delete from 'room' where 'id' not in(select 'msg_id' from 'messages');
if it don't work for you, you can try NOT EQUAL TO query
delete from 'room' where 'id' <>(select 'msg_id' from 'messages');
I have to write the following query in zend-framework2
select count(*) from
(
select * from table1
UNION
select * from table2
)
as a
where col1 = condition1 and col2 = condition2;
I have done union of two tables using -
$select1 = new Select('table1');
$select2 = new Select("table2");
$select1->combine($select2);
I don't know how to give an alias after doing the union of two tables and how to get the count of data.
After $select1->combine($select2); -
$sql = new Sql($this->tableGateway->adapter);
$select_string = $sql->getSqlStringForSqlObject($select1);
$sql_string = 'SELECT * FROM (' . $select_string . ') AS select_union WHERE col1 = condition1 and col2 = condition2';
$statement = $this->tableGateway->adapter->createStatement($sql_string);
$resultSet = $statement->execute();
$total_records = count($resultSet);
$resultSet gives data.
$total_records gives total no. of records.
The code I have below joins 5 tables and then is suppose to sort by date_timed_added. The query worked perfectly if i only join 4 tables. For some reason after the 4th table, its giving me issues. The issue is that it sorts and displays the 5th table first and then the rest follow. How can i fix it so that it sorts date_time_added properly by querying all the other tables?
//$sid is a variable that is drawn from DB
$sql = "select `client_visit`.`visit_id`, `client_visit`.
`why_visit`, `client_visit`.`date_time_added`, `client_visit`.
`just_date`, `client_visit`.`type` from `client_visit` where
`client_visit`.`system_id` = '$sid' and `client_visit`.
`added_by` = '$sid'
UNION
select `client_notes`.`note_id`, `client_notes`.`note_name`,
`client_notes`.`date_time_added`, `client_notes`.`just_date`
, `client_notes`.`type` from `client_notes` where `client_notes`.
`added_by` = '$sid'
UNION
select `client_conditions`.`med_id`, `client_conditions`.`med_name`,
`client_conditions`.`date_time_added`, `client_conditions`.`just_date`,
`client_conditions`.`type` from `client_conditions` where
`client_conditions`.`system_id` = '$sid' and `client_conditions`.
`added_by` = '$sid'
UNION
select `client_stats`.`stat_test_id`, `client_stats`.`stat_why`,
`client_stats`.`date_time_added`, `client_stats`.`just_date`,
`client_stats`.`type`
from `client_stats` where `client_stats`.`system_id` = '$sid'
and `client_stats`.`added_by` = '$sid'
UNION
select `client_documents`.`doc_id`, `client_documents`.`doc_name`,
`client_documents`.`date_time_added`, `client_documents`.`just_date`,
`client_documents`.`type` from `client_documents` where `client_documents`.
`system_id` = '$sid' and `client_documents`.`added_by` = '$sid'
ORDER BY `date_time_added` DESC LIMIT $startrow, 20";
$query = mysql_query($sql) or die ("Error: ".mysql_error());
$result = mysql_query($sql);
if ($result == "")
{
echo "";
}
echo "";
$rows = mysql_num_rows($result);
if($rows == 0)
{
}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{
//Just using these two variables i can display the same row info
//for all the other tables
$stuffid = htmlspecialchars($row['visit_id']);
$title = htmlspecialchars($row['why_visit');
}
}
}
As per the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/union.html
If you want to order the ENTIRE result set, the ORDER BY clause must be placed on the LAST query in the UNION, with each query being bracketed.
(SELECT ...)
UNION
(SELECT ...)
ORDER BY ...
sth like this should do.
SELECT Tbl1.field1
FROM ( SELECT field1 FROM table1
UNION
SELECT field1 FROM table2
) Tbl1
ORDER BY Tbl1.field1
When the result of a query exists, I want to know the name of the row(s) that have the correct results:
$query = "SELECT Id FROM Programacao WHERE ID = 1";
$curDate = date("Y-m-d H").':00:00';
$query = "SELECT Id
FROM Programacao
WHERE Data1 = '$curDate'
OR Data2 = '$curDate'
OR Data3 = '$curDate'"
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)){}
simply talking its if(Data1 == curDate)return Data1; if(Data2 == curDate)return Data2....
Sorry for my bad english.
Well it would be Programacao from your query. But if you needed it dynamically you could try functions like mysql_table_name() or mysql_field_name().
A select statement does not go into a table.
It goes into a resultset.
Resultsets do not have names, they just are.
http://en.wikipedia.org/wiki/Result_set
Perhaps you mean this? (either with UNION or UNION ALL):
$query = "
SELECT Id
, 'Data1' AS name
FROM Programacao
WHERE Data1 = '$curDate'
UNION
SELECT Id
, 'Data2'
FROM Programacao
WHERE Data2 = '$curDate'
UNION
SELECT Id
, 'Data3'
FROM Programacao
WHERE Data3 = '$curDate'
" ;
i have a function where i get the ratings of the selected user by id,
it gets the ratings from one type of things, the ratings of a diff type of things and then does a+b
i know it's not very optimized but i'm focus on making all work...
this i do it like this
function votos_usuario($id){
$previa = "SELECT id FROM preguntas WHERE id_usuario = '$id'";
$r_previo = mysql_query($previa);
$ids_p = '0, ';
while($items_previos = mysql_fetch_array($r_previo)){
$ids_p .= $items_previos['id'].", ";
//echo "ids pregunta usuario: ".$items_previos['id']."<br>";
}
$ids = substr($ids_p,0,-2);
//echo $ids;
$consulta = "SELECT valor FROM votos_pregunta WHERE id_pregunta IN ( $ids )";
//echo $consulta;
$resultado = mysql_query($consulta);
$votos_preguntas = 0;
while($voto = mysql_fetch_array($resultado)){
$votos_preguntas = $votos_preguntas + $voto['valor'];
}
//$votos_preguntas= 0;
//$votos_preguntas = mysql_query("SELECT SUM(valor) FROM votos_pregunta WHERE id_pregunta IN (SELECT id FROM preguntas WHERE id_usuario = '$id')");
$previa_r = "SELECT id FROM recetas WHERE id_usuario = '$id'";
$r_previo_r = mysql_query($previa_r);
$ids_r = '0, ';
while($items_previos_r = mysql_fetch_array($r_previo_r)){
$ids_r .= $items_previos_r['id'].", ";
//echo "ids pregunta usuario: ".$items_previos['id']."<br>";
}
$ids = substr($ids_r,0,-2);
$consulta_b = "SELECT valor FROM votos_receta WHERE id_receta IN ( $ids )";
//echo $consulta;
$resultado_b = mysql_query($consulta_b);
$votos_recetas = 0;
while($voto_r = mysql_fetch_array($resultado_b)){
$votos_recetas = $votos_recetas + $voto_r['valor'];
}
$total = $votos_preguntas + $votos_recetas;
return $total;
}
Now the Question,
how can i do it to get all users ordered by rating desc ???? i just can't see it :S
SELECT uid, SUM(Votes)
FROM (
SELECT p.id_usuario uid, SUM(vp.valor) votes
FROM preguntas p JOIN votos_pregunta vp ON p.id = vp.id_pregunta
GROUP BY p.id_usuario
UNION ALL
SELECT r.id_usuario uid, SUM(vr.valor) votes
FROM recetas r JOIN votos_receta vr ON r.id = vr.id_receta
GROUP BY r.id_usuario
) rs
GROUP BY uid
ORDER BY SUM(Votes) DESC
instead of your php loop and all the sub queries, you can use this single query to get what you want:
SELECT (
SELECT SUM(vp.valor)
FROM preguntas p JOIN votos_pregunta vp ON p.id = vp.id_pregunta
WHERE p.id_usuario = '$id')
+ (
SELECT SUM(vr.valor)
FROM recetas r JOIN votos_receta vr ON r.id = vr.id_receta
WHERE r.id_usuario = '$id'
)
Also, when you're only using the associative keys in the result array, using mysql_fetch_assoc() is much, much faster than mysql_fetch_array().
Same applies to using mysql_fetch_row() instead when you're just using the numerical keys.