SQL - Result consisted of more than one row - mysql

I'm still trying to make my first function, it creates without any errors, but when I try to use it, it gives me error - ERROR 1172 (42000): Result consisted of more than one row
Here's the function -
CREATE FUNCTION kontakti2 (mainigais CHAR(3))
RETURNS CHAR(100)
BEGIN
DECLARE returnthis CHAR(100);
SELECT CONCAT(Person.name, Person.lastName, Contacts.mobile, Contacts.email)
FROM Person JOIN Contacts on Contacts.Person_ID = Person.ID
JOIN ParentChild on ParentChild.parentID = Person.ID
JOIN ChildGroup ON ChildGroup.Person_ID = ParentChild.childID
WHERE ChildGroup.Group_ID = mainigais INTO returnthis;
RETURN returnthis;
END//
Here's table schema, just in case - http://www.imagesup.net/dm-713886347846.png
How can I get this function to display several rows?

It isn't possible to return multiple rows from a function in MySQL as it does not support table valued functions like in SQL server.

Related

return result from table that not existed on another table in codeignator

I've constructed two tables: one to list the services and another to link the service to each department.
Table 1 contains the columns [s id,s name]. [s_id,s_name].
-- The Services table, records all services for all departments. [1,Install Windows 10],[2,print Payslip].
Table 2 : services_assignments consist of columns [ss_id,ss_s_id_ss_d_id].
-- services_assignments matching the services with departments.
I need to return the service that "NOT" matched for the department example.
i tried to use JOIN with Where conditions in selection but not result as the following code.
function get_services_for_assign(){ // for assigmnets
$this->db->select('*');
$this->db->from('services');
if($this->uri->segment('2')) {
$this->db->join('services_assignments','services.sr_id = services_assignments.ss_s_id','left');
$this->db->where_not_in('services_assignments.ss_d_id',$this->uri->segment('2'));
}
//$this->db->where('sr_display','1');
$data=$this->db->get();
return $data->result();
}
On the other hand, I attempted to write it manually as seen below.
function get_services_for_assign(){ // for assigmnets
$dep=$this->uri->segment('2');
$query = "SELECT sr.sr_id FROM services AS sr WHERE sr.sr_id = (SELECT sa.ss_s_id FROM services_assignments AS sa WHERE sa.ss_d_id = 1)";
$this->db->query($query);
$data=$this->db->get();
return $data->result();
}
and I encountered the following error; I discovered numerous results that were similar to my problem, but I couldn't solve it.
A Database Error Occurred
Error Number: 1096
No tables used
SELECT *
Filename: C:/xampp/htdocs/townteam/system/database/DB_driver.php
Line Number: 691
I need your help to return the results services that were not used by the other department.
You have not stated which version of CodeIgniter you are using or what the expected behaviour is when no department id is passed.
This should work in both CI3 and CI4. If using CI4, you should probably use prepared statements. I could not find documentation on passing parameters into a multi-condition join with CI so I have written the query out in full.
$sql = <<<'SQL'
SELECT s.*
FROM services s
LEFT JOIN services_assignments sa
ON s.sr_id = sa.ss_s_id
AND sa.ss_d_id = ?
WHERE sa.ss_s_id IS NULL
AND s.sr_display = 1
SQL;
$this->db->query($sql, [$this->uri->segment('2')]);

How to make where condition always be true with field =?

I have a sql statement follow:
select * from table where id = ?
Now, problem is, l don't know whether front end will send me the value of id, if it did, this sql seem like id = 1, and if not, sql should be like id = true(fake code) to find all data
How could I write my sql?
Or, It is fundamentally wrong?
This is normally handled by using logic such as this:
select *
from table
where id = ? or ? is null;
If you don't want to pass the parameter twice or use named parameters:
select t.*
from table t cross join
(select ? as param) params
where id = params.param or params.param is null;
If you want to return all ids if the passed-in value does not exist:
select t.*
from table t
where id = ? or
not exists (select 1 from table t2 where t2.id = ?);
What you can try doing is in your code, write a function for fetching a specific record, and another function for fetching all the records from your table.
In PHP, it could be something like:
// Fetching a specific record
function getCustomerRecord($customerId) {
// Code to fetch specific record from database
}
// Fetching all records
function getAllCustomerRecords() {
// Code to fetch all records from database
}
In the function where you process requests received, check first if a value for id was passed. If a value for id was passed, call the function to fetch a specific record, making sure to pass along the value you received as an argument. Otherwise, call the function to fetch all the records from your table.
You can try doing this to get your right sql statement in PHP
function GetSqlStatement($id){
return $sql = "select * from table where id = ".$id.";";
}

MYSQL: Updating a column based on select statement with joins

I've got a select statement that returns a list of all items in a document store that have comments (stored in a separate comments table).
What I'm trying to do is to update the value of another column in public_document_store (skin_id) for all the documents that have released comments, based on the statement below.
This returns the records I want to update:
SELECT public_document_store_talkback.document_id,
public_document_store.section_id
FROM public_document_store
INNER JOIN public_document_store_talkback ON public_document_store_talkback.document_id = public_document_store.document_id
WHERE public_document_store_talkback.is_released = 1
AND public_document_store_talkback.is_rejected = 0
AND public_document_store.section_id = 10;
I've tried to update the skin_id field like this:
Update public_document_store SET skin_id = 6
WHERE document_id IN (Select... [as per the statement above] )
But this returns an error:
[Err] 1241 - Operand should contain 1 column(s)
I've tried various other permutations based on other answers here, but without any luck (My knowledge of SQL is pretty basic, so apologies if I am missing something obvious here)
Any ideas how I can make this work would be much appreciated.
Your SELECT query needs only a little modification to convert it into an UPDATE statement,
UPDATE public_document_store a
INNER JOIN public_document_store_talkback b
ON b.document_id = a.document_id
SET a.skin_id = 6
WHERE b.is_released = 1 AND
b.is_rejected = 0 AND
a.section_id = 10

Help with MySQL Coalesce and Stored Procedures

I'm (attempting) to write a MySQL stored procedure that parses a large text file. Part of what this procedure does is check to see if the entities (in this case, government contractors) named in each record are already contained in the db. (This is a follow up to this question.) This is my first stored procedure and so I'm sure I've wondered off the rails here, and I would appreciated any help.
Here's what I have right now (after declaring the variables):
-- try and fetch first organization (a government agency)
SET agency = COALESCE(SELECT org_agency_o_id FROM orgs_agencies WHERE org_agency_code = maj_agency_cat,SELECT min(org_id) FROM orgs WHERE org_name LIKE CONCAT('U.S. ',SUBSTRING(maj_agency_cat,5)))
-- check to see if that worked
IF agency = NULL THEN
INSERT INTO orgs (org_name,org_name_length,org_type,org_sub_types) VALUES (CONCAT('U.S. ',SUBSTRING(maj_agency_cat,5)),LENGTH(CONCAT('U.S. ',SUBSTRING(maj_agency_cat,5))),'org','Org,GovernmentEntity,Federal,Agency');
SET agency = LAST_INSERT_ID();
END IF;
-- try and fetch second organization
SET org = COALESCE(SELECT MIN(org_id) FROM orgs WHERE org_name IN (vendorname, vendoralternatename, vendorlegalorganizationname, vendordoingasbusinessname), SELECT MIN(org_alias_org_id) FROM orgs_aliases WHERE org_alias in (endorname, vendoralternatename, vendorlegalorganizationname, vendordoingasbusinessname))
IF org = NULL THEN
INSERT INTO orgs(org_name,org_name_length,org_type,org_sub_types,org_created) VALUES (vendorname,LENGTH(vendorname),'org','org',DATE());
SET org = LAST_INSERT_ID();
END IF
Right now MySQL is throwing an error on the line:
SET agency = COALESCE(SELECT org_agency_o_id FROM orgs_agencies WHERE org_agency_code = maj_agency_cat,SELECT min(org_id) FROM orgs WHERE org_name LIKE CONCAT('U.S. ',SUBSTRING(maj_agency_cat,5)))
'maj_agency_cat' is a variable that I declare at the beginning of the procedure and then is assigned dynamically using a cursor that goes through my staging data. The full stored procedure can be viewed here.
I'm sure I'm missing something basic and would appreciate any help.
Try wrapping another () around the inner SELECT statements in your COALESCE arguments. Otherwise, they are not treated as subqueries to be executed first and the value returned, but as query objects passed into COALESCE, which is not a valid argument type for COALESCE:
SET agency = COALESCE((SELECT ..), (SELECT ..))

Store procedure select all fields from One table using join

I am very frustrated from linq to sql when dealing with many to many relationship with the skip extension. It doesn't allow me to use joinned queries. Not sure it is the case for SQL server 2005 but I am currently using SQL Server 2000.
Now I consider to write a store procedure to fetch a table that is matched by two tables e.g. Album_Photo (Album->Album_Photo<-Photo) and Photo table and only want the Photos data so I match the Album's ID with Album_Photo and use that ID to match the photo. In the store procedure I am just fetch all the joinned data. After that in the linq to sql, I create a new Album object.
e.g.
var albums = (from r in result
where (modifier_id == r.ModifierID || user_id == r.UserID)
select new Album() {
Name = r.Name,
UserID = r.UserID,
ModifierID = r.ModifierID,
ID = r.ID,
DateCreated = r.DateCreated,
Description = r.Description,
Filename = r.Filename
}).AsQueryable();
I used the AsQueryable to get the result as a IQueryable rather than IEnumerable. Later I want to do something with the collection, it gives me this error:
System.InvalidOperationException: The query results cannot be enumerated more than once.
It sounds like you have a situation where the query has already executed by the time you are want to filter it later in your code.
Can you do something like...
var albums = (blah blah blah).AsQueryable().Where(filterClause) when you have enough info to process
what happens if you try albums.where(filter) later on in the code? Is this what you are trying?