I'm trying to make a SQL query and I have some problems with it.
CREATE table entries (
id_entry INT PRIMARY KEY,
);
CREATE table entry_date (
entry_date_id INT PRIMARY KEY,
entry_id INT,
entry_price INT,
entry_date TEXT,
);
for each entry, there is several dates.
I'd like to select the entries.entry_id where that entry have, for example, the dates '23/03/2013' and '24/03/2013' linked to it.
The two dates are stored into an array:
$data = array('ci' => '23/03/2013', 'co' => '24/03/2013');
I store the dates in text for practical purpose in my treatment.
I use Zend_Db so my query is constructed like that:
$select = $table->select ()->from ( 'entries' )->setIntegrityCheck ( false );
if ($data ['ci'] != NULL) {
$select->join ( array (
'entry_dates' => 'entry_dates'
), 'entries.id_entry = entry_dates.entry_id' );
$select->where ( 'entry_dates.entry_date = ?', $data ['ci'] );
}
if ($data ['co']) {
if ($data['ci'] == NULL) {
$select->join ( array (
'entry_dates' => 'entry_dates'
), 'entries.id_entry = entry_dates.entry_id' );}
$select->where ( 'entry_dates.entry_date = ?', $data ['co'] );
}
which gives :
SELECT `entries`.*, `entry_date`.*
FROM `entries`
INNER JOIN `entry_dates`
ON entries.id_entry = entry_dates.entry_id
WHERE (entry_dates.entry_date = '23/03/2013')
AND (entry_dates.entry_date = '24/03/2013')
And, well ... It doesn't work.
When I fetch my $select, I get nothing.
I guess I miss something in my request when I do the WHERE ... AND , what should I do to get the correct output ? The real request being really long, I'd like to avoid another long subselect if possible.
It can be done in two way, either with a self-join on the entry_date table:
SELECT `entries`.entry_id
FROM `entries`
INNER JOIN `entry_dates` AS ed1
ON entries.id_entry = ed1.entry_id
INNER JOIN `entry_dates` AS ed2
ON entries.id_entry = ed2.entry_id
WHERE ed1.entry_date = '23/03/2013'
AND ed2.entry_date = '24/03/2013'
Or with an aggregate
SELECT `entries`.entry_id
FROM `entries`
INNER JOIN `entry_dates` AS ed
WHERE ed.entry_date = '23/03/2013'
OR ed2.entry_date = '24/03/2013'
GROUP BY `entries`.entry_id
HAVING COUNT(DISTINCT ed.entry_date)=2
Related
im trying to return a product that can have three images per product.
something like this:
{
product_id: 1,
product_name:"test",
category_id_fk: 1,
product_price: 12,
product_desc:"lorem-ipsum",
product_images:[path1, path2, path3]
}
Here is what i have got so far,
create table product(
product_id serial not null primary key,
category_id_fk int not null references category(category_id) ,
product_image_fk int not null references product_images(product_images_id),
product_name varchar(50) not null,
product_price int not null,
product_desc varchar(200) not null);
create table product_images(
product_images_id serial not null primary key,
product_image_one varchar(150) not null,
product_image_two varchar(150) not null,
product_image_three varchar(150) not null);
this is the query im using for the product details page
SELECT * FROM product WHERE category_id_fk = ? AND product_id = ?;
Im new to SQL and have been really having a tough time with this specifically, would
appreciate it a lot if anyone could explain to me what im doing wrong or if you have any tips for me.
I don't know what programming language you are using, but in this case I assume you are using a programming language like PHP as a REST API provider because you are using prepared statements
Here is the query:
SELECT * FROM `product_images` `pi` LEFT JOIN `product` `p`
ON `pi`.`product_images_id` = `p`.`product_image_fk` WHERE
`p`.`product_id` = ? AND `p`.`category_id_fk` = ?
Then on your PHP scripts you can make it like this:
$sql = "SELECT * FROM `product_images` `pi` LEFT JOIN `product` `p`
ON `pi`.`product_images_id` = `p`.`product_image_fk` WHERE
`p`.`product_id` = ? AND `p`.`category_id_fk` = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $productId, $categoryId);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
$jsonArray = [
"product_id" => $row["product_id"],
"product_name" => $row["product_name"],
"category_id_fk" => $row["category_id_fk"],
"product_price" => $row["product_price"],
"product_desc" => $row["product_desc"],
"product_images" => [$row["product_image_one"], $row["product_image_two"], $row["product_image_three"]]
];
$expectedJson = json_encode($jsonArray);
And you can do whatever you want to the json maybe by storing it on the json file or to print it as http response
SELECT JSON_OBJECT( 'product_id', p.product_id,
'product_name', p.product_name,
'category_id_fk', p.category_id_fk,
'product_price', p.product_price,
'product_desc', p.product_desc,
'product_images', JSON_ARRAY(pi.product_image_one,
pi.product_image_two,
pi.product_image_three) ) output
FROM product p
JOIN product_images pi ON p.product_image_fk = pi.product_images_id;
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=16f3a1fe3619c6c3601983d4c00de07d
I am struggling to get correct results with this. I want to test if both, or either, exist. In results table, 'michael' exists while 'mike' does not.
$stmt = $dbnet->prepare("
SELECT * FROM
(SELECT cats AS cats1 FROM results WHERE name = :original) AS a,
(SELECT cats AS cats2 FROM results WHERE name = :parsed) AS b
");
$binding = array(
'original' => 'michael',
'parsed' => 'mike'
);
$stmt->execute($binding);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
//if there was a result then output
if($results)
{
echo '<pre>'.print_r($results,1).'</pre>';
}
I get no results with this even though 'michael' is in the database.
If I test for 'original' => 'michael', 'parsed' => 'michael' I get results...both the same of course since I tested the same value for each :
Array
(
[0] => Array
(
[cats1] => 6,11
[cats2] => 6,11
)
)
What I expect is one of the following :
no results meaning neither michael or mike exist
result for cats1 and empty for cats2 (michael exists mike does not)
empty for cats1 and result for cats2 (mike exists michael does not)
No, I cannot use WHERE name = 'michael' OR name = 'mike' because what I do after changes depending if both have results or just one or the other.
This is working as epxected... both always needs a result even if that is empty to return correctly.
$stmt = $dbnet->prepare("
SELECT
IFNULL( (SELECT cats AS cats1 FROM results WHERE name = :original), '') AS a,
IFNULL( (SELECT cats AS cats2 FROM results WHERE name = :parsed), '') AS b
");
Suppose I defined music as a table and gave it 3 columns: album, artist, and track:
CREATE TABLE music (
id int auto_increment primary key,
album varchar(45) not null,
artist varchar(30) not null,
track int(8)
);
Now I want another table releasedy which contains a column:
'Year' and the table music
I suppose for that I have to bind some row from table music with year from table releasedy in another table. So I can know which year contains which musics. If I'm not wrong I have to do that with foreign key. How should I proceed?
You do not want "a table in a table", instead you want to match records from one table with records from another table in a query. You can create a view on top of this query and use the view later as it if were a regular table.
As you guessed, establish a foreign key relationship, then JOIN the two tables.
There is no "table in a table", only tables and relations between them.
Table releasedy will have 2 columns, musicId & year. musicId is the foreign key to your music table.
Join (as you called bind) these two:
SELECT *
FROM music m
INNER JOIN releasedy r ON m.id = r.musicId
WHERE year = ..
Which is all overkill in this example but it illustrates the "binding" you want.
class Functions {
public function getRows($sql){
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$data[] = $row;
}
return $data;
}
public function getMusicData(){
$data = $this->getRows("SELECT * FROM music");
return base64_encode(serialize($data));
}
}
$func = new Functions();
$music = $func->getMusicData();
$sql = "insert into releasedy (id,Year) values (NULL,'".$music."')";
mysql_query($sql);
$id = 'your necessary id'; $read = "select * from releasedy where id = ".(int)$id; $data = mysql_query($read); $musics = unserialize(base64_decode($data['Year'])); foreach($musics as $music){ // do something }
i need to take only the items from the table "__sobi2_item" that are in the same country of the user.And use this results for the rest of the function Showupdatelisting. This is my php script:
<?php
function showUpdatedListing()
{
//i found the user country field value...
global $database;
$user =& JFactory::getUser();
$userId = $user->get( 'id' );
$sql = "SELECT (id) FROM #__community_fields WHERE fieldcode= 'FIELD_COUNTRY'";
$database->setQuery( $sql );
$fieldID = $database->loadResult();
$sql = "SELECT (value) FROM #__community_fields_values WHERE field_id= {$fieldID} && user_id= {$userId}";
$database->setQuery( $sql );
$usercountry = $database->loadResult();
// From all the entries i take only ones that have country field like the user has...
$query = "SELECT `data_txt`, `itemid`, `fieldid` FROM `#__sobi2_fields_data` WHERE (`fieldid` = 6) AND ('data_txt' = {$usercountry})";
$database->setQuery($query);
$ResultsArray = $database->loadObjectList();
// We need something here like a Query to load only the entries from $ResultsArray... ??
//....instead of this...
$config =& sobi2Config::getInstance();
$database = $config->getDb();
$now = $config->getTimeAndDate();
$query = "SELECT itemid FROM #__sobi2_item WHERE (published = 1 AND publish_down > '{$now}' OR publish_down = '{$config->nullDate}') ORDER BY last_update DESC LIMIT 0, 30";
$database->setQuery($query);
$sids = $database->loadResultArray();
// ......... show update function goes on...
?>
can anyone help me to connect and adjust these query? thanks.
NB:with the last query (4) i need to filter items of the $ResultsArray taking only ones published and ordering them by last_update. i know it is wrong and now there is no connection with the query before. This is how i have tables in mysql:
_sobi2_fields_data:
itemid
fieldid
data_txt --->(is a description column for each field)
_sobi2_item:
itemid
published --->( 1 if true, 0 if false )
last_update --->(date of the last update for the item, also equal to the publication date if there are no changes)
thanks.
I don't know what you are trying to ask as well. Your last query (number 4) doesn't make sense to me, how is it linked to the above queries?
[EDIT] I've linked your 4th table above assuming itemid is the primary key for the items in sobi2_item table and that the value is linked to the sobi_fields_data table via itemid.
SELECT
cf.id,
sfd.data_txt,
sfd.itemid,
sfd.fieldid
FROM #__community_fields cf
INNER JOIN #__community_fields_values cfv ON cf.id=cfv.field_id
INNER JOIN #__sobi2_fields_data sfd ON cfv.value=sfd.data_txt
INNER JOIN #__sobi2_item si ON sfd.itemid=si.itemid
WHERE cf.fieldcode='FIELD_COUNTRY'
AND cfv.user_id=$userId
AND sfd.fieldid=6
AND si.published=1
AND (si.publish_down > '{$now}' OR si.publish_down = '{$config->nullDate}')
ORDER BY si.last_update DESC LIMIT 0, 30
Good luck!
I need a bit of help.
I have (reference?) table with columns: id , user_id , key , value
It is pretty much a user profile table
and I would like to have SQL (I am using zend db table, but general SQL help will do) where I get "all 'user_id's where 'key' is somekey and 'value' is somevalue of that user_id but only if it also matches where 'key' is otherkey and 'value' is othervalue".
In other words I want to get users that have shoes of maker NIKE and color BLACK.
therefore 'key' is shoecolor and 'value' is BLACK and also another row with same user_id has 'key' is shoemaker and 'value' is NIKE.
This is what I could come up with, but doesn't work.
SELECT `user_profiles`.* FROM `user_profiles` WHERE
(`key` = 'shoecolor' AND `value` = 'BLACK') AND
(`key` = 'shoemaker' AND `value` = 'NIKE')
In case someone is knowledgable in zend db:
$where = array('shoecolor' => 'BLACK', 'shoemaker' => 'NIKE');
foreach ($where as $key => $value) {
$sql = $db->quoteInto('key = ?', $key);
$sql .= ' AND ' . $db->quoteInto('value = ?', $value);
$select->where($sql);
}
// make unique result
//$select->groupBy('user_id');
$resultSet = $zendTableInstance->fetchAll($select);
Please Help.
Thanx.
Because the key/value pair is in the row, your query is looking for a key that is 3 AND 4. No value can be 3 and 4 at the same time ;)
SELECT user_profiles.* FROM user_profiles WHERE (key = 3 AND value = 21) AND (key = 4 AND value = 55)
will not work.
You could do a join on yourself, and check for these values?
SELECT user_profiles.*
FROM user_profiles up1
JOIN user_profiles up2 ON up1.user_id = up2.user_id
WHERE
(up1.key = 3 AND up1.value = 21)
AND (up2.key = 4 AND up2.value = 55)